const { get_fst_file } = require("../utils/file_tool");
const { BaseCommand } = require("./base");

class ReadOnlyExcelCommand extends BaseCommand {
    async execute() {
        const xlsx = require("xlsx");
        const SpreadsheetColumn = require("spreadsheet-column");
        const sc = new SpreadsheetColumn();
        const filename = get_fst_file(this.selfData.src);
        const ret = xlsx.readFile(filename, this.selfData.options);
        if (this.selfData.sheets_array !== false) {
            ret.SheetsArray = {};
            for (const sheetName in ret.Sheets) {
                const sheetData = ret.Sheets[sheetName];
                const sheetArray = [];
                // "A1:Y71"
                /** @type {string[]} */
                const refs = sheetData["!ref"].split(":");
                const colBeg = sc.fromStr(/[A-Z]+/.exec(refs[0])[0]);
                const rowBeg = /[0-9]+/.exec(refs[0])[0];
                const colEnd = sc.fromStr(/[A-Z]+/.exec(refs[1])[0]);
                const rowEnd = /[0-9]+/.exec(refs[1])[0];
                for (let row = rowBeg; row <= rowEnd; ++row) {
                    const rowData = [];
                    for (let col = colBeg; col <= colEnd; ++col) {
                        const cell = sheetData[`${sc.fromInt(col)}${row}`];
                        rowData.push(cell?.v);
                    }
                    sheetArray.push(rowData);
                }
                ret.SheetsArray[sheetName] = sheetArray;
            }
        }
        return ret;
    }
}

module.exports = {
    ReadOnlyExcelCommand,
};
